package etcd

import (
	"context"
	"fmt"
	clientv3 "go.etcd.io/etcd/client/v3"
	"k8s.io/apimachinery/pkg/util/json"
	"sigs.k8s.io/controller-runtime/pkg/log"
	"time"
)

var (
	client *clientv3.Client
)

func Init() (err error) {

	client, err = clientv3.New(clientv3.Config{
		Endpoints:   []string{"114.132.230.45:2379"},
		DialTimeout: time.Second * 5,
	})
	if err != nil {
		fmt.Printf("connect to etcd failed, err:%v", err)
		return
	}
	return nil
}

// updateEtcdConf
func UpdateConf(conf []CollectEntry) error {
	defer client.Close()
	// put
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	marshal, err := json.Marshal(conf)
	if err != nil {
		log.Log.Info("conf []CollectEntry compare fail.......")
		return err
	}
	log.Log.Info("conf []CollectEntry compare success......." + string(marshal))
	_, err = client.Put(ctx, "collect_log_conf", string(marshal))
	if err != nil {
		fmt.Println("etcd put fail........")
		return err
	}
	return nil
}
